package pl.edu.pb.wi.cookbook.controller;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.SerializationUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import pl.edu.pb.wi.cookbook.form.MailForm;
import pl.edu.pb.wi.cookbook.service.EmailService;

import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskHandle;

@Controller
public class SendEmailsController {
    private static final Logger log = Logger
            .getLogger(SendEmailsController.class.getName());
    private static final String VALID_CRON_HEADER = "X-AppEngine-Cron";
    private EmailService emailService;
    public static final String EMAIL_QUEUE_NAME = "email-queue";

    @Autowired
    public SendEmailsController(EmailService emailService) {
        super();
        this.emailService = emailService;
    }

    @RequestMapping(value = "/email/send/all", method = RequestMethod.GET)
    public @ResponseBody
    String sendPendingEmails(HttpServletRequest request) throws Exception {
        if (StringUtils.equals(request.getHeader(VALID_CRON_HEADER), "true")) {
            Queue queue = QueueFactory.getQueue(EMAIL_QUEUE_NAME);
            List<TaskHandle> tasks = null;
            int totalProcessed = 0;
            while (!((tasks = queue.leaseTasks(20, TimeUnit.SECONDS, 5))
                    .isEmpty())) {
                for (TaskHandle task : tasks) {
                    MailForm mailForm = (MailForm) SerializationUtils
                            .deserialize(task.getPayload());
                    emailService.sendMail(mailForm.getEmail(),
                            mailForm.getValidationHash());
                    ++totalProcessed;
                    log.info(String
                            .format("Sending verification e-mail to: '%s' Total emails processed: %d",
                                    mailForm.getEmail(), totalProcessed));
                }

                queue.deleteTask(tasks);
            }
        } else {
            log.warning("Someone unauthorized tried to access send mail controller.");
            throw new Exception();
        }

        return "OK";
    }
}
